package com.qianfeng.biquge.service.impl;


import com.qianfeng.biquge.constans.ResultCode;
import com.qianfeng.biquge.exceptions.AddDataException;
import com.qianfeng.biquge.exceptions.DeleteDataException;
import com.qianfeng.biquge.exceptions.QueryDataException;
import com.qianfeng.biquge.exceptions.UpdateDataException;
import com.qianfeng.biquge.mapper.CategorieMapper;
import com.qianfeng.biquge.pojo.Categories;
import com.qianfeng.biquge.service.CategorieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

@Service
@Transactional
public class CategorieServiceImpl implements CategorieService {

    @Autowired
    private CategorieMapper categorieMapper;


    @Override
    public Categories addCategorie(String categoryName) throws UnsupportedEncodingException {

        if (categoryName==null || categoryName.equals("")){

            throw new AddDataException("添加图书分类失败,名称不能为空", ResultCode.CATEGORIE_NAME_NULL);

        }

        String decode = URLDecoder.decode(categoryName, "UTF-8");

        categorieMapper.addCategorie(decode);

        Categories categorie = categorieMapper.getCategorieByCategoryName(decode);

        return categorie;


    }

    @Override
    public List<Categories> getAllOKCategorie() {

        List<Categories> categoriesList = categorieMapper.getAllOKCategorie();

        if (categoriesList==null){

            throw new QueryDataException("查询图书分类失败",ResultCode.DATA_NOT_EXIST);

        }

        return categoriesList;


    }

    @Override
    public List<Categories> getAllCategorieIsDelete() {

        List<Categories> categoriesList = categorieMapper.getAllCategorieIsDelete();

        if (categoriesList==null){

            throw new QueryDataException("查询图书分类失败",ResultCode.DATA_NOT_EXIST);

        }

        return categoriesList;

    }

    @Override
    public int updateCategorie(Categories categories) {

        if (categories==null || categories.getCategoryid()==null || categories.getCategoryname()==null){

            throw new UpdateDataException("修改图书分类失败,ID为空",ResultCode.CATEGORIE_PRIMARY_NULL);

        }

        int i = categorieMapper.updateCategorie(categories);

        if (i<=0){

            throw new UpdateDataException("修改图书分类失败,ID不正确",ResultCode.CATEGORIE_PRIMARY_NULL);

        }

        return i;


    }

    @Override
    public int deleteCategorie(Long categoryId) {

        if (categoryId==null || categoryId <= 0){

            throw new DeleteDataException("删除图书分类失败,ID不正确",ResultCode.CATEGORIE_PRIMARY_NULL);

        }

        int i = categorieMapper.deleteCategorie(categoryId);

        if (i<=0){

            throw new DeleteDataException("删除图书分类失败,ID不存在",ResultCode.CATEGORIE_PRIMARY_NULL);

        }

        return i;


    }
}
